package vashion.azeroth.back.controller.item;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import vashion.azeroth.back.controller.base.BaseController;
import vashion.azeroth.contant.CommonErrorEnum;
import vashion.azeroth.contant.GenericErrorEnum;
import vashion.azeroth.contant.ItemErrorEnum;
import vashion.azeroth.contant.item.ItemStatusEnum;
import vashion.azeroth.core.item.pojo.ForestDO;
import vashion.azeroth.core.item.pojo.ItemBrandDO;
import vashion.azeroth.core.item.pojo.ItemDO;
import vashion.azeroth.core.item.pojo.ItemSkuDO;
import vashion.azeroth.core.item.pojo.ItemTagDO;
import vashion.azeroth.core.item.pojo.PropertyValueDO;
import vashion.azeroth.core.item.query.ItemQueryDO;
import vashion.azeroth.core.lenux.pojo.LenuxApiResult;
import vashion.azeroth.core.lenux.pojo.LenuxProduct;
import vashion.azeroth.core.manager.forest.BaseForestManager;
import vashion.azeroth.core.manager.item.BaseItemBrandManager;
import vashion.azeroth.core.manager.item.BaseItemSkuManager;
import vashion.azeroth.core.manager.item.ItemReadManger;
import vashion.azeroth.core.manager.item.ItemTagManager;
import vashion.azeroth.core.manager.item.ItemWriteManager;
import vashion.azeroth.core.manager.item.LenuxItemWriteManager;
import vashion.azeroth.core.manager.item.TagManager;
import vashion.azeroth.core.manager.item.YvogueItemWriteManager;
import vashion.azeroth.core.manager.personal.PersonalMemberManager;
import vashion.azeroth.back.core.excel.ReadExcel;
import vashion.azeroth.common.http.HttpContentGetter;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.base.BaseService;
import vashion.azeroth.core.service.item.ItemRecommendService;
import vashion.azeroth.core.yvogue.pojo.YvogueProduct;
import vashion.azeroth.core.yvogue.pojo.YvogueProductList;
import vashion.azeroth.core.yvogue.sftp.SFTPUtil;
import vashion.azeroth.core.yvogue.xml.XMLUtil;

@Controller
@RequestMapping("back/item")
public class BackItemController<T> extends BaseController {

	private final static Logger log = LoggerFactory.getLogger(BackItemController.class);

	@Value("#{settings['defaultSupplierName']}")
	private String defaultSupplierName;

	@Autowired
	private ItemReadManger itemReadManger;

	@Autowired
	private ItemWriteManager itemWriteManager;

	@Autowired
	private BaseItemSkuManager baseItemSkuManager;

	@Autowired
	private ItemRecommendService itemRecommendService;

	@Autowired
	private PersonalMemberManager personalMemberManager;

	@Autowired
	private BaseForestManager baseForestManager;

	@Autowired
	private BaseItemBrandManager baseItemBrandManager;

	@Autowired
	private YvogueItemWriteManager yvogueItemWriteManager;

	@Autowired
	private LenuxItemWriteManager lenuxItemWriteManager;

	@Autowired
	private TagManager tagManager;

	@Autowired
	private ItemTagManager itemTagManager;

	/**
	 * @param request
	 * @param itemDO
	 * @param miniSkuList
	 * @return 发布商品结果
	 */
	@RequestMapping("publishItem.htm")
	public ModelAndView publishItem(Model model, HttpServletRequest request, @ModelAttribute("itemDO") ItemDO itemDO,
			@RequestParam(value = "miniSkuList", required = false) String miniSkuList,
			@RequestParam(value = "tagListString", required = false) String tagListString) {

		if (null == itemDO) {
			model.addAttribute("errorMsg", ItemErrorEnum.ITEM_ARG_ERROR.getErrorMessage());
			return new ModelAndView("forward:getItemList.htm");
		}
		// 检查发布的供应商情况
		PersonalMember supplier = personalMemberManager.get(itemDO.getUserId());
		if (null == supplier) {
			model.addAttribute("errorMsg", GenericErrorEnum.NOT_EXIST.getErrorMessage());
			model.addAttribute("memberName", itemDO.getMemberName());
			return new ModelAndView("forward:gotoPublishItemPage.htm");
		}
		// 获取品牌名字
		ItemBrandDO brand = baseItemBrandManager.get(itemDO.getBrandId());
		if (null != brand) {
			itemDO.setBrandTitle(brand.getTitle());
		}
		List<ItemSkuDO> skuDOList = parseSku(miniSkuList, itemDO);
		// 设置总库存
		int stock = itemDO.getStock();
		if (!CollectionUtils.isEmpty(skuDOList) && stock <= 0) {
			for (ItemSkuDO itemSkuDO : skuDOList) {
				stock += itemSkuDO.getStock();
			}
			itemDO.setStock(stock);
		}
		ApiResult<Boolean> publishResult = itemWriteManager.publishItem(itemDO, skuDOList, tagListString	,
				getLoginUserId(request));
		if (publishResult.isSuccess() && publishResult.getData()) {
			model.addAttribute("msg", "商品发布成功");
			model.addAttribute("memberName", itemDO.getMemberName());
		} else {
			model.addAttribute("errorMsg", publishResult.getErrorMsg());
		}
		return new ModelAndView("forward:gotoPublishItemPage.htm");
	}

	/**
	 * 修改商品的细节
	 * 
	 * @param model
	 * @param item
	 * @param miniSkuList
	 * @param itemDescBack
	 * @param itemCodeBack
	 * @param itemCodeOrigin
	 * @param itemListPageNum
	 * @param request
	 * @return 商品修改结果
	 */
	@RequestMapping("updateItem.htm")
	public ModelAndView updateItem(Model model, @ModelAttribute("itemDO") ItemDO item,
			@RequestParam(value = "miniSkuList", required = false) String miniSkuList,
			@RequestParam(value = "tagListString", required = false) String tagListString,
			@RequestParam(value = "itemDescBack", required = false) String itemDescBack,
			@RequestParam(value = "itemCodeBack", required = false) String itemCodeBack,
			@RequestParam(value = "memberNameBack", required = false) String memberNameBack,
			@RequestParam(value = "itemCodeOrigin", required = false) String itemCodeOrigin,
			@RequestParam(value = "itemListPageNum", required = false) int itemListPageNum,
			HttpServletRequest request) {

		String errorMsg = "";
		if (null == item) {
			errorMsg += ItemErrorEnum.ITEM_ARG_ERROR.getErrorMessage();
		} else {
			model.addAttribute("itemDescBack", itemDescBack);
			model.addAttribute("itemCodeBack", itemCodeBack);
			model.addAttribute("memberNameBack", memberNameBack);
			model.addAttribute("itemCodeOrigin", itemCodeOrigin);
			model.addAttribute("itemListPageNum", itemListPageNum);
			List<ItemSkuDO> skuDOList = parseSku(miniSkuList, item);
			// 获取品牌名字
			ItemBrandDO brand = baseItemBrandManager.get(item.getBrandId());
			if (null != brand) {
				item.setBrandTitle(brand.getTitle());
			}
			if (itemWriteManager.updateItem(item, tagListString, getLoginUserId(request)).isSuccess()) {
				if (CollectionUtils.isEmpty(skuDOList)) {
					Boolean updateSkuResult = baseItemSkuManager.updateSkuList(skuDOList);
					if (updateSkuResult) {
						model.addAttribute("msg", "成功修改商品。");
					} else {
						errorMsg += ItemErrorEnum.ITEM_ARG_ERROR.getErrorMessage();
					}
				}
			} else {
				errorMsg += ItemErrorEnum.SYSTEM_ERROR.getErrorMessage();
			}
		}
		if (!StringUtils.isBlank(errorMsg)) {
			model.addAttribute("errorMsg", errorMsg);
		}
		return new ModelAndView("forward:gotoUpdateItemPage.htm");
	}

	/**
	 * 修改商品的商品编码
	 * 
	 * @param model
	 * @param item
	 * @param itemDescBack
	 * @param itemCodeBack
	 * @param itemListPageNum
	 * @param request
	 * @return 修改结果
	 */
	@RequestMapping("updateItemCode.htm")
	public String updateItemCode(Model model, @ModelAttribute("item") ItemDO item,
			@RequestParam(value = "itemDescBack", required = false) String itemDescBack,
			@RequestParam(value = "itemCodeBack", required = false) String itemCodeBack,
			@RequestParam(value = "memberNameBack", required = false) String memberNameBack,
			@RequestParam(value = "itemCodeOrigin", required = false) String itemCodeOrigin,
			@RequestParam(value = "itemListPageNum", required = false) int itemListPageNum,
			HttpServletRequest request) {

		String errorMsg = "";
		model.addAttribute("itemDO", item);
		if (null == item || item.getId() <= 0 || StringUtils.isBlank(item.getItemCode())) {
			errorMsg += ItemErrorEnum.ITEM_ARG_ERROR.getErrorMessage() + "。";
		}
		model.addAttribute("itemDescBack", itemDescBack);
		model.addAttribute("itemCodeBack", itemCodeBack);
		model.addAttribute("memberNameBack", memberNameBack);
		model.addAttribute("itemCodeOrigin", itemCodeOrigin);
		model.addAttribute("itemListPageNum", itemListPageNum);
		if (StringUtils.isBlank(errorMsg)) {
			ItemDO newItem = new ItemDO();
			newItem.setId(item.getId());
			newItem.setItemCode(item.getItemCode());
			if (itemWriteManager.updateItem(newItem, null, getLoginUserId(request)).isSuccess()) {
				model.addAttribute("msg", "成功修改商品编码。");
			} else {
				errorMsg += ItemErrorEnum.SYSTEM_ERROR.getErrorMessage() + "。";
			}
		}

		if (!StringUtils.isBlank(errorMsg)) {
			model.addAttribute("errorMsg", errorMsg);
		}
		return "/item/editItemCode";

	}

	private List<ItemSkuDO> parseSku(String miniSkuList, ItemDO itemDO) {

		List<ItemSkuDO> resultList = Lists.newArrayList();
		if (StringUtils.isEmpty(miniSkuList)) {
			return resultList;
		}

		JsonFactory factory = new JsonFactory();
		ObjectMapper mapper = new ObjectMapper(factory);
		TypeReference<List<HashMap<String, String>>> typeRef = new TypeReference<List<HashMap<String, String>>>() {
		};
		List<HashMap<String, String>> jsonList = Lists.newArrayList();
		try {
			jsonList = mapper.readValue(miniSkuList, typeRef);
		} catch (Exception e) {
			log.error("mapper.readValue error miniSkuList=" + miniSkuList, e);
			return resultList;
		}
		for (HashMap<String, String> map : jsonList) {
			ItemSkuDO itemSkuDO = new ItemSkuDO();
			itemSkuDO.setGmtModified(new Date());
			itemSkuDO.setGmtCreate(new Date());
			itemSkuDO.setStock(NumberUtils.toInt(map.get("stock")));
			itemSkuDO.setPropertyValueIdArr(map.get("ids"));
			if (!StringUtils.isEmpty(map.get("pic"))) {
				itemSkuDO.setPic(map.get("pic"));
			} else {
				itemSkuDO.setPic(itemDO.getPic());
			}
			// 设置id等属性
			if (map.containsKey("id")) {
				itemSkuDO.setId(NumberUtils.toLong(map.get("id")));
			}
			itemSkuDO.setItemId(itemDO.getId());
			itemSkuDO.setUserId(itemDO.getUserId());
			itemSkuDO.setItemPic(itemDO.getPic());
			itemSkuDO.setItemPrice(itemDO.getPrice());
			itemSkuDO.setVipPrice(itemDO.getVipPrice());
			itemSkuDO.setItemTitle(itemDO.getTitle());
			itemSkuDO.setCategoryId(itemDO.getCategoryId());

			resultList.add(itemSkuDO);
		}

		return resultList;
	}

	/**
	 * @param model
	 * @param itemQueryDO
	 * @param brandIds
	 * @param categoryIds
	 * @return 显示商品列表的页面
	 */
	@RequestMapping("getItemList.htm")
	public String getItemList(Model model, @ModelAttribute("itemQueryDO") ItemQueryDO itemQueryDO,
			@RequestParam(value = "brandIds", required = false) String brandIds,
			@RequestParam(value = "categoryIds", required = false) String categoryIds) {
		if (itemQueryDO.getPageNO() <= 0) {
			itemQueryDO.setPageNO(1);
		}
		// 查找member的ID，设置入查询条件
		String memberNameQuery = itemQueryDO.getMemberName();
		if (null != memberNameQuery) {
			PersonalMember memberQuery = personalMemberManager.getMemberByName(itemQueryDO.getMemberName());
			if (null != memberQuery) {
				itemQueryDO.setUserId(memberQuery.getMemberId());
				itemQueryDO.setMemberName(null);
			}
		}
		itemQueryDO.setStart((itemQueryDO.getPageNO() - 1) * itemQueryDO.getPageSize());
		List<ItemDO> itemList = itemReadManger.getItemListforBackAdmin(itemQueryDO, brandIds, categoryIds).getData();
		int itemCount = itemReadManger.countQueryItemForBackAdmin(itemQueryDO, brandIds, categoryIds).getData();
		for (ItemDO itemDOTemp : itemList) {
			PersonalMember memberTemp = personalMemberManager.get(itemDOTemp.getUserId());
			if (null != memberTemp) {
				itemDOTemp.setMemberName(memberTemp.getMemberName());
			}
		}
		ItemDO itemPage = new ItemDO();
		itemPage.setPageNum(itemQueryDO.getPageNO());
		itemPage.setPageSize(itemQueryDO.getPageSize());
		itemPage.setFirstRow(itemQueryDO.getStart());
		BaseService page = new BaseService();
		page.initPages(itemPage, itemCount);
		itemQueryDO.setStart(itemPage.getFirstRow());
		model.addAttribute("itemList", itemList);
		itemQueryDO.setMemberName(memberNameQuery);
		model.addAttribute("item", itemQueryDO);
		model.addAttribute("page", page);
		return "/item/itemList";
	}

	/**
	 * @param word
	 * @return 推荐词
	 */
	@RequestMapping("getRecommendWord.htm")
	@ResponseBody
	public ApiResult<List<String>> getRecommendWord(@RequestParam(value = "word") String word) {
		return itemReadManger.getRecommendTitle(word);
	}

	/**
	 * @param itemId
	 * @param userId
	 * @return 推荐商品列表
	 */
	@RequestMapping("recommendItemList.htm")
	@ResponseBody
	public ApiResult<List<ItemDO>> recommendItem(@RequestParam(value = "itemId", required = false) Long itemId,
			@RequestParam(value = "userId", required = false) Long userId) {
		// 商品没有推荐
		// if (null != itemId && itemId > 0) {
		// return itemRecommendService.recommendItemByItemId(itemId);
		// } else
		if (null != userId && userId > 0) {
			return itemRecommendService.recommendItemByUserId(userId);
		} else {
			return ApiResult.newErrorResult(CommonErrorEnum.SYSTEM_ERROR.getErrorCode(),
					CommonErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
	}

	/**
	 * 下架商品
	 * 
	 * @param model
	 * @param itemDO
	 * @param request
	 * @return 商品下架结果
	 */
	@RequestMapping("downItem.htm")
	public ModelAndView downItem(Model model, @ModelAttribute("ItemDO") ItemDO itemDO, HttpServletRequest request) {
		ItemDO itemDODown = new ItemDO();
		itemDODown.setId(itemDO.getId());
		itemDODown.setStatus(ItemStatusEnum.SYSTEM_DELETE.getStatus());
		ApiResult<Boolean> downResult = itemWriteManager.updateItem(itemDODown, null, getLoginUserId(request));
		if (downResult.isSuccess()) {
			model.addAttribute("msg", "商品冻结成功。");
		} else {
			model.addAttribute("errorMsg", "商品冻结失败。");
		}
		return new ModelAndView("forward:getItemList.htm");
	}

	/**
	 * 启用商品
	 * 
	 * @param model
	 * @param itemDO
	 * @param request
	 * @return 商品上架结果
	 */
	@RequestMapping("resumeItem.htm")
	public ModelAndView resumeItem(Model model, @ModelAttribute("ItemDO") ItemDO itemDO, HttpServletRequest request) {
		ItemDO itemDOResume = new ItemDO();
		itemDOResume.setId(itemDO.getId());
		itemDOResume.setStatus(ItemStatusEnum.ORIGIN_STATUS.getStatus());
		ApiResult<Boolean> resumeResult = itemWriteManager.updateItem(itemDOResume, null, getLoginUserId(request));
		if (resumeResult.isSuccess()) {
			model.addAttribute("msg", "商品启用成功。");
		} else {
			model.addAttribute("errorMsg", "商品启用失败。");
		}
		return new ModelAndView("forward:getItemList.htm");
	}

	@RequestMapping("getItemDetail.htm")
	@ResponseBody
	public ApiResult<ItemDO> getItemDetail(@RequestParam(value = "itemId", required = false) long itemId,
			@RequestParam(value = "needSku", required = false) boolean needSku) {

		if (itemId <= 0) {

			return ApiResult.newErrorResult(ItemErrorEnum.ITEM_ARG_ERROR.getErrorCode(),
					ItemErrorEnum.ITEM_ARG_ERROR.getErrorMessage());
		}
		return itemReadManger.getItemDetail(itemId, needSku);
	}

	@RequestMapping("updateItemSkuNum.htm")
	@ResponseBody
	public ApiResult<Boolean> updateItemSkuNum() {

		return ApiResult.newSuccessResult(baseItemSkuManager.updateItemSkuNum(394, 2, true));
	}

	/**
	 * @param model
	 * @param item
	 * @param itemDescBack
	 * @param itemCodeBack
	 * @param itemCodeOrigin
	 * @param itemListPageNum
	 * @param request
	 * @return 编辑商品编码页面
	 */
	@RequestMapping("gotoEditItemCodePage.htm")
	public String gotoEditItemCodePage(Model model, @ModelAttribute("item") ItemDO item,
			@RequestParam(value = "itemDescBack", required = false) String itemDescBack,
			@RequestParam(value = "itemCodeBack", required = false) String itemCodeBack,
			@RequestParam(value = "memberNameBack", required = false) String memberNameBack,
			@RequestParam(value = "itemCodeOrigin", required = false) String itemCodeOrigin,
			@RequestParam(value = "itemListPageNum", required = false) int itemListPageNum,
			HttpServletRequest request) {
		model.addAttribute("item", item);
		model.addAttribute("itemDescBack", itemDescBack);
		model.addAttribute("itemCodeBack", itemCodeBack);
		model.addAttribute("memberNameBack", memberNameBack);
		model.addAttribute("itemCodeOrigin", itemCodeOrigin);
		model.addAttribute("itemListPageNum", itemListPageNum);
		return "/item/editItemCode";
	}

	/**
	 * @param model
	 * @param id
	 * @param itemDescBack
	 * @param itemCodeBack
	 * @param itemCodeOrigin
	 * @param itemListPageNum
	 * @param request
	 * @return 编辑商品页面
	 */
	@RequestMapping("gotoUpdateItemPage.htm")
	public String gotoUpdateItemPage(Model model, @RequestParam(value = "id", required = false) Long id,
			@RequestParam(value = "itemDescBack", required = false) String itemDescBack,
			@RequestParam(value = "itemCodeBack", required = false) String itemCodeBack,
			@RequestParam(value = "memberNameBack", required = false) String memberNameBack,
			@RequestParam(value = "itemCodeOrigin", required = false) String itemCodeOrigin,
			@RequestParam(value = "itemListPageNum", required = false) int itemListPageNum,
			HttpServletRequest request) {
		ApiResult<ItemDO> itemResult = itemReadManger.getItemDetailforBackAdmin(id);
		ItemDO item = null;
		if (itemResult.isSuccess()) {
			if (null != itemResult.getData()) {
				item = itemResult.getData();
			} else {
				model.addAttribute("errorMsg", ItemErrorEnum.ITEM_QUERY_ERROR.getErrorMessage());
			}
		} else {
			model.addAttribute("errorMsg", itemResult.getErrorMsg());
		}
		// 查询商品已有的标签
		List<ItemTagDO> itemTagList = Lists.newArrayList();
		ApiResult<List<ItemTagDO>> itemTagListResult = itemTagManager.findByItemId(id);
		if (null != itemTagListResult && itemTagListResult.isSuccess() && null != itemTagListResult.getData()) {
			itemTagList = itemTagListResult.getData();
		}
		model.addAttribute("itemTagList", itemTagList);
		model.addAttribute("item", item);
		model.addAttribute("descPicList", descPicString2descPicList(item.getDescPic()));
		model.addAttribute("itemDescBack", itemDescBack);
		model.addAttribute("itemCodeBack", itemCodeBack);
		model.addAttribute("memberNameBack", memberNameBack);
		model.addAttribute("itemCodeOrigin", itemCodeOrigin);
		model.addAttribute("itemListPageNum", itemListPageNum);
		return "/item/editItem";
	}

	/**
	 * @param model
	 * @param memberName
	 * @param request
	 * @return 发布商品的页面
	 */
	@RequestMapping("gotoPublishItemPage.htm")
	public String gotoPublishItemPage(Model model,
			@RequestParam(value = "memberName", required = false) String memberName, HttpServletRequest request) {
		if (StringUtils.isBlank(memberName)) {
			memberName = this.defaultSupplierName;
		}
		PersonalMember supplier = personalMemberManager.getMemberByName(memberName);
		if (null == supplier) {
			String errorMsg = "无法发布商品，因为供应商" + GenericErrorEnum.NOT_EXIST.getErrorMessage();
			model.addAttribute("errorMsg", errorMsg);
			return "/item/publishItem";
		}
		ApiResult<Map<ForestDO, List<ForestDO>>> forestTreeResult = baseForestManager.getForestTree();
		if (forestTreeResult.isSuccess() && null != forestTreeResult.getData()) {
			Map<ForestDO, List<ForestDO>> forestTree = forestTreeResult.getData();
			List<ForestDO> forestList = Lists.newArrayList();
			for (Map.Entry<ForestDO, List<ForestDO>> forestTreeEntry : forestTree.entrySet()) {
				ForestDO parentForest = forestTreeEntry.getKey();
				parentForest.setFullTitle(parentForest.getTitle());
				forestList.add(parentForest);
				for (ForestDO childForest : forestTreeEntry.getValue()) {
					childForest.setFullTitle((parentForest.getTitle() + " - " + childForest.getTitle()));
					forestList.add(childForest);
				}
			}
			model.addAttribute("supplier", supplier);
			model.addAttribute("categoryList", forestList);
		}
		return "/item/publishItem";
	}

	/**
	 * 上传xls，xlsx文件批量更新商品的存货
	 *
	 * @param model
	 * @param member
	 * @param request
	 * @return 商品更新结果
	 */
	@RequestMapping("batchUpdateItemsStock.htm")
	@ResponseBody
	public ApiResult<String> batchUpdateItemsStock(Model model, @ModelAttribute("member") PersonalMember member,
			HttpServletResponse response, HttpServletRequest request, @RequestParam("file") MultipartFile file) {
		log.info("AddController ..batchUpdateItemsStock() start");
		StringBuffer resultMsg = new StringBuffer();
		// 判断文件是否为空
		if (file == null)
			return null;
		// 获取文件名
		String fileName = file.getOriginalFilename();
		// 进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）
		long size = file.getSize();
		if (fileName == null || ("").equals(fileName) && size == 0)
			return null;

		// 批量导入。参数：文件名，文件。
		boolean result = false;
		// 创建处理EXCEL
		ReadExcel readExcel = new ReadExcel();
		// 解析excel，获取商品信息集合。
		Map<String, List<PropertyValueDO>> skuListResult;
		try {
			skuListResult = readExcel.getExcelInfo(fileName, file);
			if (null == skuListResult) {
				return ApiResult.newErrorResult(ItemErrorEnum.SYSTEM_ERROR.getErrorCode(), readExcel.getErrorInfo());
			}
			result = true;
			// 更新库存
			for (Map.Entry<String, List<PropertyValueDO>> entry : skuListResult.entrySet()) {
				Boolean updateResult;
				updateResult = itemWriteManager.updateItemSku(entry.getKey(), entry.getValue(), member.getMemberId(),
						getLoginUserId(request));
				System.out.println("Code:" + entry.getKey() + ", value" + entry.getValue());
				if (!updateResult) {
					resultMsg.append("商品编码为：").append(entry.getKey())
							.append("的商品更新失败，可能该商品未上传，请先上传商品再更新库存，可能该商品尺寸有误，请核实并修正上传文件的内容;<br />");
				}
			}
			if (resultMsg.length() > 0) {
				resultMsg = new StringBuffer("更新失败的商品：<br />").append(resultMsg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ApiResult.newErrorResult(ItemErrorEnum.SYSTEM_ERROR.getErrorCode(), readExcel.getErrorInfo());
		}
		if (result) {
			resultMsg = new StringBuffer("批量更新商品库存成功。<br />").append(resultMsg);
		} else {
			return ApiResult.newErrorResult(ItemErrorEnum.SYSTEM_ERROR.getErrorCode(),
					"批量更新商品库存失败：" + readExcel.getErrorInfo());
		}
		ApiResult<String> updateResult = ApiResult.newSuccessResult(resultMsg.toString().substring(0, 500));
		return updateResult;
	}

	/**
	 * 获取并保存yvogue商品
	 *
	 * @return
	 */
	@RequestMapping("publishYvogueItems.htm")
	@ResponseBody
	public ApiResult<Boolean> publishYvogueItems() {
		SFTPUtil sftp = new SFTPUtil("inventory", "Ihxy&L", "121.40.188.248", 22);
		try {
			sftp.login();

			String xmlStr = sftp.download("./", "inventory.xml");
			// System.out.println(xmlStr);
			sftp.logout();
			YvogueProductList yvogueProductList = (YvogueProductList) XMLUtil.convertXmlStrToObject(
					YvogueProductList.class, xmlStr.replaceAll("<inventory>", "").replaceAll("</inventory>", ""));
			Iterator<YvogueProduct> it = yvogueProductList.iterator();
			while (it.hasNext()) {
				YvogueProduct yvogueItem = (YvogueProduct) it.next();
				yvogueItemWriteManager.publishItem(yvogueItem, "15900966755");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ApiResult.newSuccessResult(true);
	}

	/**
	 * 获取并保存lenux商品
	 *
	 * @return
	 */
	@RequestMapping("publishLenuxItems.htm")
	@ResponseBody
	public ApiResult<Boolean> publishLenuxItems() {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
		String timestamp = sdf.format(new Date());
		Map<String, String> nameValueMap = Maps.<String, String>newHashMap();
		nameValueMap.put("appid", "shxtest");
		nameValueMap.put("pageSize", "100");
		nameValueMap.put("timestamp", timestamp);
		List<LenuxProduct> allProductList = Lists.newArrayList();

		try {
			log.info("同步新增货存开始");
			for (int page = 1; page < 2000; page++) {
				nameValueMap.put("page", String.valueOf(page));
				String returnMessage = HttpContentGetter.getContentString("http://open.lenuxchina.com/api/item/page",
						nameValueMap, null);
				log.info("returnMessage = " + returnMessage);
				LenuxApiResult result = null;
				if (StringUtils.isNotEmpty(returnMessage)) {
					result = JSON.parseObject(returnMessage, LenuxApiResult.class);
					if (CollectionUtils.isEmpty(result.getData())) {
						break;
					} else {
						allProductList.addAll(result.getData());
					}
				}
			}
			int i = 0;
			int successInt = 0;
			for (LenuxProduct product : allProductList) {
				ApiResult<Boolean> publishResult = lenuxItemWriteManager.publishItem(product, "15101103668");
				i++;
				if (publishResult.isSuccess() && publishResult.getData()) {
					successInt++;
				}
			}
			log.info("i = " + i);
			log.info("success i = " + successInt);
			log.info("同步新增货存结束");
		} catch (Exception e) {
			log.error("同步新增货存错误：" + e.getMessage());
			e.printStackTrace();
		}
		return ApiResult.newSuccessResult(true);
	}

	/**
	 * 给所有商品添加默认标签
	 *
	 * @return
	 */
	@RequestMapping("addDefaultTagsForAllItems.htm")
	@ResponseBody
	public ApiResult<Boolean> addDefaultTagsForAllItems(HttpServletRequest request) {
		ItemQueryDO itemQueryDO = new ItemQueryDO();
		itemQueryDO.setPageSize(200000);
		ApiResult<List<ItemDO>> itemListResult = itemReadManger.getItemListforBackAdmin(itemQueryDO, null, null);
		if (null != itemListResult && !CollectionUtils.isEmpty(itemListResult.getData())) {
			for (ItemDO item : itemListResult.getData()) {
				itemTagManager.addDefaultTagsForItem(item, getLoginUserId(request));
			}
		}
		return ApiResult.newSuccessResult(true);
	}

	/**
	 * 给商品添加默认标签
	 *
	 * @return
	 */
	@RequestMapping("publishDefaultTags.htm")
	@ResponseBody
	public ApiResult<Boolean> publishDefaultTags(HttpServletRequest request) {
		return tagManager.publishDefaultTags(getLoginUserId(request));
	}

	/**
	 * 前往设置商品标签页面
	 * 
	 * @param model
	 * @param itemId
	 * @return 设置页面
	 */
	@RequestMapping("gotoUpdateTagsForItemPage.htm")
	public String gotoUpdateTagsForItemPage(Model model, @RequestParam(value = "itemId", required = true) long itemId) {
		ApiResult<ItemDO> itemDOResult = itemReadManger.getItemDetail(itemId, false);
		ItemDO itemDO = new ItemDO();
		// 查询商品
		List<ItemTagDO> itemTagList = Lists.newArrayList();
		if (null != itemDOResult && itemDOResult.isSuccess() && null != itemDOResult.getData()) {
			itemDO = itemDOResult.getData();
		}
		// 查询商品已有的标签
		ApiResult<List<ItemTagDO>> itemTagListResult = itemTagManager.findByItemId(itemId);
		if (null != itemTagListResult && itemTagListResult.isSuccess() && null != itemTagListResult.getData()) {
			itemTagList = itemTagListResult.getData();
		}
		model.addAttribute("item", itemDO);
		model.addAttribute("itemTagList", itemTagList);
		return "/item/updateTagsForItem";
	}

	/**
	 * 给商品设置标签
	 * 
	 * @param request
	 * @param itemId
	 * @param tagListString
	 * @return 设置结果
	 */
	@RequestMapping("updateTagsForItem.htm")
	@ResponseBody
	public ApiResult<Boolean> updateTagsForItem(HttpServletRequest request,
			@RequestParam(value = "itemId", required = true) long itemId,
			@RequestParam(value = "tagListString", required = false) String tagListString) {
		return itemTagManager.updateTagsForItem(itemId, tagListString, getLoginUserId(request), true);
	}

	/**
	 * @param descPicString
	 * @return 描述图片的地址列表
	 */
	private List<String> descPicString2descPicList(String descPicString) {
		if (StringUtils.isNotEmpty(descPicString)) {
			String[] descPicArray = descPicString.replaceAll(";", ",").split(",");
			List<String> descPicList = new ArrayList<String>();
			for (String descPic : descPicArray) {
				if (!descPic.trim().isEmpty()) {
					descPicList.add(descPic);
				}
			}
			if (!descPicList.isEmpty()) {
				return descPicList;
			}
		}
		return null;
	}

}
